// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import AdminLayout from '@/components/AdminLayout.vue'
import Dashboard from '@/components/Dashboard.vue'
import StudentsManagement from '@/components/StudentsManagement.vue'
import TeachersManagement from '@/components/TeachersManagement.vue'
import CoursesManagement from '@/components/CoursesManagement.vue'
import Analytics from '@/components/Analytics.vue'
import Settings from '@/components/Settings.vue'
import Login from '@/components/Login.vue'
import Register from '@/components/Register.vue'
import ForgotPassword from '@/components/ForgotPassword.vue'
import ResetPassword from '@/components/ResetPassword.vue'
import NotFound from '@/components/NotFound.vue'
import NewsManagement from '@/components/NewsManagement.vue'
import Public from '@/components/Public.vue'
// 新增：信息完善页面
import StudentProfileCompletion from '@/components/StudentProfileCompletion.vue'
import TeacherProfileCompletion from '@/components/TeacherProfileCompletion.vue'
import TeacherDashboard from '@/components/TeacherDashboard.vue'
import StudentDashboard from '@/components/StudentDashboard.vue'

import TeacherLayout from '@/components/TeacherLayout.vue'
import StudentLayout from '@/components/StudentLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: ForgotPassword,
    meta: {
      title: '忘记密码',
      requiresAuth: false
    }
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: ResetPassword,
    meta: {
      title: '重置密码',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Public',
    component: Public,
    meta: {
      title: '首页',
      requiresAuth: false
    }
  },
  // 新增：信息完善路由组
  {
    path: '/complete-profile',
    meta: {
      requiresAuth: true,
      requiresProfileCompletion: false // 这个页面不需要完善信息检查
    },
    children: [
      {
        path: 'student',
        name: 'StudentProfileCompletion',
        component: StudentProfileCompletion,
        meta: {
          title: '完善学员信息',
          requiresAuth: true,
          userType: 'student',
          requiresProfileCompletion: false
        }
      },
      {
        path: 'teacher',
        name: 'TeacherProfileCompletion',
        component: TeacherProfileCompletion,
        meta: {
          title: '完善教师信息',
          requiresAuth: true,
          userType: 'teacher',
          requiresProfileCompletion: false
        }
      }
    ]
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: {
      requiresAuth: true,
      requiresProfileCompletion: true // 管理后台需要完善信息
    },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表盘',
          icon: 'icon-dashboard',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/students',
        name: 'Students',
        component: StudentsManagement,
        meta: {
          title: '学员管理',
          icon: 'icon-users',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/teachers',
        name: 'Teachers',
        component: TeachersManagement,
        meta: {
          title: '教师管理',
          icon: 'icon-package',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/courses',
        name: 'Courses',
        component: CoursesManagement,
        meta: {
          title: '课程管理',
          icon: 'icon-shopping-cart',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/resources',
        name: 'Resources',
        component: () => import('@/components/ResourceManagement.vue'),
        meta: {
          title: '资源管理',
          icon: 'icon-folder',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/signups',
        name: 'SignUps',
        component: () => import('@/components/SignUpManagement.vue'),
        meta: {
          title: '报名管理',
          icon: 'icon-user-plus',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/news',
        name: 'News',
        component: NewsManagement,
        meta: {
          title: '咨询与公告管理',
          icon: 'icon-newspaper',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/honors',
        name: 'Honors',
        component: () => import('@/components/HonorsManagement.vue'),
        meta: {
          title: '荣誉管理',
          icon: 'icon-award',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/analytics',
        name: 'Analytics',
        component: Analytics,
        meta: {
          title: '数据分析',
          icon: 'icon-bar-chart',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      },
      {
        path: '/settings',
        name: 'Settings',
        component: Settings,
        meta: {
          title: '系统设置',
          icon: 'icon-settings',
          requiresAuth: true,
          requiresProfileCompletion: true
        }
      }
    ]
  },

   {
    path: '/teacher',
    component: TeacherLayout,
    meta: {
      requiresAuth: true,
      requiresProfileCompletion: true,
      userType: 'teacher'
    },
    children: [
      {
        path: '',
        redirect: '/teacher/dashboard'
      },
      {
        path: '/teacher/dashboard',
        name: 'TeacherDashboard',
        component: TeacherDashboard,
        meta: {
          title: '教师仪表盘',
          icon: 'icon-dashboard',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'teacher'
        }
      },
      // 可以添加更多教师专用路由
      {
        path: '/teacher/courses',
        name: 'TeacherCourses',
        component: CoursesManagement,
        meta: {
          title: '我的课程',
          icon: 'icon-book',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'teacher'
        }
      },
      {
        path: '/teacher/students',
        name: 'TeacherStudents',
        component: StudentsManagement,
        meta: {
          title: '我的学员',
          icon: 'icon-users',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'teacher'
        }
      }
    ]
  },
  {
    path: '/student',
    component: StudentLayout,
    meta: {
      requiresAuth: true,
      requiresProfileCompletion: true,
      userType: 'student'
    },
    children: [
      {
        path: '',
        redirect: '/student/dashboard'
      },
      {
        path: '/student/dashboard',
        name: 'StudentDashboard',
        component: StudentDashboard,
        meta: {
          title: '学员仪表盘',
          icon: 'icon-dashboard',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'student'
        }
      },
      // 可以添加更多学生专用路由
      {
        path: '/student/courses',
        name: 'StudentCourses',
        component: CoursesManagement,
        meta: {
          title: '我的课程',
          icon: 'icon-book',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'student'
        }
      },
      {
        path: '/student/progress',
        name: 'StudentProgress',
        component: Analytics,
        meta: {
          title: '学习进度',
          icon: 'icon-bar-chart',
          requiresAuth: true,
          requiresProfileCompletion: true,
          userType: 'student'
        }
      }
    ]
  },

  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面未找到'
    }
  }
]

const router = createRouter({
  history: createWebHistory('/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 修复后的路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫:', { 
    to: to.path, 
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    requiresProfileCompletion: to.meta.requiresProfileCompletion
  })

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 农民技能提升就业培训大数据平台`
  }

  // 动态导入 auth store
  const { useAuthStore } = await import('@/stores/auth')
  const authStore = useAuthStore()

  console.log('认证状态:', {
    isAuthenticated: authStore.isAuthenticated,
    userType: authStore.userType,
    isProfileCompleted: authStore.isProfileCompleted,
    hasToken: !!authStore.accessToken
  })

  // 1. 处理不需要认证的页面（公开页面）
  if (to.meta.requiresAuth === false) {
    // 如果是已登录用户访问登录相关页面，重定向到合适的仪表盘
    if (['Login', 'Register', 'ForgotPassword', 'ResetPassword'].includes(to.name)) {
      if (authStore.isAuthenticated) {
        console.log('已登录用户访问登录页，跳转到仪表盘')
        
        const userType = authStore.userType
        let redirectPath = '/dashboard'
        
        if (userType === 'teacher') {
          redirectPath = '/teacher/dashboard'
        } else if (userType === 'student') {
          redirectPath = '/student/dashboard'
        }
        
        next(redirectPath)
        return
      }
    }
    
    // 如果是已登录用户访问首页，重定向到合适的仪表盘
    if (to.name === 'Public' && authStore.isAuthenticated) {
      console.log('已登录用户访问首页，跳转到仪表盘')
      
      const userType = authStore.userType
      let redirectPath = '/dashboard'
      
      if (userType === 'teacher') {
        redirectPath = '/teacher/dashboard'
      } else if (userType === 'student') {
        redirectPath = '/student/dashboard'
      }
      
      next(redirectPath)
      return
    }
    
    // 未登录用户访问公开页面，直接放行
    next()
    return
  }

  // 2. 处理需要认证的页面
  if (!authStore.isAuthenticated) {
    console.log('需要认证但未登录，跳转到登录页')
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  // 3. 如果token过期但有refresh token，尝试刷新
  if (authStore.isTokenExpired && authStore.refreshToken) {
    try {
      console.log('Token过期，尝试刷新')
      await authStore.refreshAccessToken()
      // 刷新后重新获取用户信息
      await authStore.fetchUserProfile()
    } catch (error) {
      console.error('Token refresh failed:', error)
      authStore.clearAuth()
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  // 4. 检查用户类型权限（在信息完善检查之前）
  if (to.meta.userType && to.meta.userType !== authStore.userType) {
    console.log('用户类型不匹配，重定向到合适的仪表盘')
    const userType = authStore.userType
    
    let redirectPath = '/dashboard'
    if (userType === 'teacher') {
      redirectPath = '/teacher/dashboard'
    } else if (userType === 'student') {
      redirectPath = '/student/dashboard'
    }
    
    next(redirectPath)
    return
  }

  // 5. 检查信息完善页面的访问权限
  const isProfileCompletionPage = to.path.startsWith('/complete-profile/')
  
  if (isProfileCompletionPage) {
    // 如果用户已经完善了信息，不允许再次访问信息完善页面
    if (authStore.isProfileCompleted) {
      console.log('用户已完善信息，重定向到对应仪表盘')
      const userType = authStore.userType
      
      let redirectPath = '/dashboard'
      if (userType === 'teacher') {
        redirectPath = '/teacher/dashboard'
      } else if (userType === 'student') {
        redirectPath = '/student/dashboard'
      }
      
      next(redirectPath)
      return
    }
    
    // 如果用户未完善信息，检查用户类型是否匹配页面类型
    if (to.name === 'StudentProfileCompletion' && authStore.userType !== 'student') {
      console.log('非学员用户访问学员信息完善页面')
      next('/complete-profile/teacher')
      return
    }
    
    if (to.name === 'TeacherProfileCompletion' && authStore.userType !== 'teacher') {
      console.log('非教师用户访问教师信息完善页面')
      next('/complete-profile/student')
      return
    }
    
    // 用户类型匹配且未完善信息，允许访问
    next()
    return
  }

  // 6. 检查其他页面是否需要完善信息
  if (to.meta.requiresProfileCompletion !== false && !authStore.isProfileCompleted) {
    const userType = authStore.userType
    
    if (userType === 'student') {
      console.log('学员需要完善信息，跳转到学员信息完善页面')
      next('/complete-profile/student')
      return
    } else if (userType === 'teacher') {
      console.log('教师需要完善信息，跳转到教师信息完善页面')
      next('/complete-profile/teacher')
      return
    }
  }

  // 7. 所有检查通过，放行
  next()
})

// 路由错误处理
router.onError((error) => {
  console.error('Router error:', error)
})

export default router